package com.example.config;

import com.example.constant.GatewayEnum;
import com.example.pojo.vo.RouteVo;
import com.example.tools.RedisTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.factory.StripPrefixGatewayFilterFactory;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Author: hualao
 * @Version: 0.0.1V
 * @Date: 2018/11/19
 * @Description: 网关路由初始化
 **/
@Slf4j
@Configuration
public class GatewayConfig {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Bean
    @RefreshScope
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        StripPrefixGatewayFilterFactory.Config config = new StripPrefixGatewayFilterFactory.Config();
        config.setParts(1);

        RouteLocatorBuilder.Builder routeLocator = builder.routes();

        List<RouteVo> lists = RedisTools.hget(stringRedisTemplate, GatewayEnum.ROUTE_LIST.getKey(),RouteVo.class);

        log.info("加载网关路由配置 --> {}",lists);

        lists.forEach(routeVo -> routeLocator.route(routeVo.getId(),
                r -> r.path(routeVo.getPath()).and().weight(routeVo.getGroup(),
                        routeVo.getWeight()).filters(f -> f.stripPrefix(1)).uri(routeVo.getUri())));

        return routeLocator.build();
    }


    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
